var gulp = require('gulp'),
    cheerio = require('gulp-cheerio'),
    domSrc = require('gulp-dom-src'),
    concat = require('gulp-concat'),
    cssmin = require('gulp-cssmin'),
    useref = require('gulp-useref'),
    minifyCss = require('gulp-minify-css'),
    runSequence = require('run-sequence'),
    uglify = require('gulp-uglify'),
    clean = require('gulp-clean'),
    jshint = require('gulp-jshint'),
    rev = require('gulp-rev'),
    csslint = require('gulp-csslint'),
    stylish = require('jshint-stylish'),
    revReplace = require('gulp-rev-replace'),
    revCollector = require('gulp-rev-collector'),
    imagemin = require('gulp-imagemin'),
    ossSync = require('gulp-oss-sync'),
    rename = require("gulp-rename"),
    replace = require('gulp-replace'),
    babel = require("gulp-babel"),
    assetpaths = require('gulp-assetpaths'),
    through = require('through2'),
    htmlmin = require('gulp-htmlmin'),
    webp = require('gulp-webp'),
    zip = require('gulp-zip'),
    autoprefixer = require('gulp-autoprefixer'),
    gulpif = require('gulp-if');

var fs = require('fs'),
    path = require('path'),
    del = require('del'),
    mergeStream = require('merge-stream'),
    exec = require('child_process').exec;

var config = {
    name: 'wd-picc',
    version: 'v1.0.0',
    oss: `http://image.fcyun.com/wd-picc/`,
    replaceFileArr: [],
    projSrc: `F:/workspace/newPicc/picc-admin/src/main/resources`
};

config.ossDoMain = `${config.oss}${config.version}/`;

const ossConfig = {
    connect: {
        accessKeyId: 'nfIeLiRQ0NQ6pvyf',
        accessKeySecret: 'SYZTfDUz7bEEcKJKlWiIcHiispzioG',
        region: 'oss-cn-beijing',
        bucket: 'fcyun'
    },
    setting: {
        dir: `/fc-picc/${config.version}`,
        noClean: false,
        force: true,
        quiet: true
    },
    controls: {
        headers: {
            'Cache-Control': 'max-age=' + 60 * 60 * 24 * 365 * 10,
            'Access-Control-Allow-Origin': '*'
        }
    }
};
//-----------------------------------------------------------------------------------------------------------
gulp.task('main', function (done) {
    // return runSequence(['_clean'], ['_login', '_templates'], ['_rev_js', '_rev_css',], ['_production'], ['_html'], ['_replaceAllFile'], ['_oss', '_htmlmin', '_jsmin'], done);
    return runSequence(['_clean'], ['_templates'], ['_rev_css'], ['_rev_js'], ['_html'], ['_htmlmin'], ['_build_css', '_build_js', '_build_images', '_build_html'], ['_zip'], ['_open'], done);
});
gulp.task('copy', function (done) {
    return runSequence(['_clean_t'], ['_copy_html', '_copy_js', '_copy_css', '_copy_images'], ['_zip_t'], ['_open_t'], done)
})

gulp.task('_open_t', done => {
    console.log(`编译完成`)
    exec(`explorer ${path.join(__dirname, "./")}`, (error, stdout, stderr) => {
        done();
    });
})
gulp.task('_zip_t', done => {
    return gulp.src('./taijiao/**/*.*')
        .pipe(zip('taijiao.zip'))
        .pipe(gulp.dest('./'))
})

gulp.task('_copy_html', done => {
    return gulp.src('./*.html')
        .pipe(gulp.dest('./taijiao'))
})
gulp.task('_copy_js', done => {
    return gulp.src('./js/**/*.*')
        .pipe(gulp.dest('./taijiao/js'))
})
gulp.task('_copy_css', done => {
    return gulp.src('./css/**/*.*')
        .pipe(gulp.dest('./taijiao/css'))
})
gulp.task('_copy_images', done => {
    return gulp.src('./images/**/*.*')
        .pipe(gulp.dest('./taijiao/images'))
})
gulp.task('_open', done => {
    console.log(`编译完成`)
    exec(`explorer ${path.join(__dirname, "./dist")}`, (error, stdout, stderr) => {
        done();
    });
})

gulp.task('_zip', done => {
    return gulp.src('./dist/build/**/*.*')
        .pipe(zip('build.zip'))
        .pipe(gulp.dest('./dist'))
})

gulp.task('_build_css', done => {
    return gulp.src('./dist/css/*.*').pipe(gulp.dest('./dist/build/static/css'))
})
gulp.task('_build_images', done => {
    return gulp.src('./dist/images/*.*').pipe(gulp.dest('./dist/build/static/images'))
})
gulp.task('_build_js', done => {
    return gulp.src('./dist/js/*.*').pipe(gulp.dest('./dist/build/static/js'))
})
gulp.task('_build_html', done => {
    return gulp.src('./dist/*.html').pipe(gulp.dest('./dist/build/templates'))
})
gulp.task('_rev_static', done => {
    return gulp.src('./images/*.*')
        .pipe(rev())
        .pipe(gulp.dest('./dist/images'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./dist/rev/images'))
})

gulp.task('_rev_js', done => {
    return gulp.src(['./dist/rev/**/*.json', './js/*.js'])
        .pipe(revCollector())
        .pipe(rev())
        .pipe(gulp.dest('./dist/js/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./dist/rev/js/'));
});

gulp.task('_rev_css', ['_rev_static'], done => {
    return gulp.src(['./dist/rev/**/*.json', './css/*.css'])
        .pipe(revCollector())
        .pipe(rev())
        .pipe(gulp.dest('./dist/css/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./dist/rev/css/'));
})


gulp.task('_production', done => {
    return gulp.src('./dist/static/js/wd-env-*.js')
        .pipe(replace(/.+/, function (str) {
            return 'var ENV="production";';
        }))
        .pipe(gulp.dest('./dist/static/js/'))
});

gulp.task('_login', function (done) {
    return gulp.src([path.resolve(config.projSrc, './templates/login.html')])
        .pipe(replace('</html>', function (m) {
            return `<script>console.log('发版时间：${new Date().Format("yyyy-MM-dd-hh:mm")}')</script>${m}`;
        }))
        .pipe(gulp.dest(path.resolve(config.projSrc, './templates/')));
});

gulp.task('_templates', function (done) {
    return gulp.src('./*.html')
        .pipe(gulp.dest('./dist/'));
});


gulp.task('_js', done => {
    return gulp.src([path.resolve(config.projSrc, './static/**/*.js')])
        .pipe(gulp.dest('./dist/static/'))
});


gulp.task('_html', function (done) {
    return gulp.src(['./dist/rev/**/*.json', './dist/*.html'])
        .pipe(revCollector())
        .pipe(useref())
        .pipe(gulpif('*.js', babel({
            presets: ['es2015']
        })))
        .pipe(gulpif('*.js', uglify().on('error', function (err) {
            console.log(err);
            this.emit('end');
        })))
        .pipe(gulpif('*.css', autoprefixer({
            browsers: ['last 20 versions'],
            cascade: true,
            remove: true
        })))
        .pipe(gulpif('*.css', minifyCss()))
        .pipe(gulp.dest('./dist/'))
});

gulp.task('_htmlmin', function (done) {
    return gulp.src('./dist/*.html')
        .pipe(htmlmin({
            removeComments: true, //清除HTML注释
            collapseWhitespace: true, //压缩HTML
            collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input />
            removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
            removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
            removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
            minifyJS: true, //压缩页面JS
            minifyCSS: true //压缩页面CSS
        }))
        .pipe(gulp.dest('./dist/'))
});

/**
 * 压缩业务逻辑js
 */
gulp.task('_jsmin', function (done) {
    return gulp.src('./dist/static/modules/**/*.js')
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(uglify().on('error', function (err) {
            console.log(err);
            this.emit('end');
        }))
        .pipe(gulp.dest(path.resolve(config.projSrc, './static/' + config.version + '/modules/')))
});

gulp.task('_replaceAllFile', function (done) {
    var arr = [];
    config.replaceFileArr.forEach(file => {
        var projFileSrc = path.resolve(config.projSrc, file.replace(/\-\w+\.html/, '.html').replace('dist/', ''));
        del.sync([projFileSrc], {
            force: true
        });
        arr.push(gulp.src(file)
            .pipe(rename(function (path) {
                path.basename = path.basename.replace(/\-\w+$/, '');
            }))
            .pipe(gulp.dest(projFileSrc.replace(/\w+\.html$/, ''))))
    });
    return mergeStream(arr);
})

gulp.task('_oss', function (done) {
    return gulp
        .src([
            `./dist/build/${config.version}/**`,
            './dist/static/**/*.png',
            './dist/static/**/*.gif',
            './dist/static/**/*.jpg',
            './dist/static/**/*.svg',
            './dist/static/**/*.svg',
            './dist/static/**/*.ttf',
            './dist/static/**/*.woff',
            './dist/static/**/*.eot',
            './dist/static/**/*.woff2',
        ])
        //.pipe(ossSync(ossConfig))
        .pipe(gulp.dest(path.resolve(config.projSrc, './static/' + config.version)));
});

gulp.task('_clean', function () {
    return gulp.src('dist', {
        read: false
    }).pipe(clean());
});

gulp.task('_clean_t', function () {
    return gulp.src('./taijiao', {
        read: false
    }).pipe(clean());
});
gulp.task('url', ['_clean'], function () {
    return gulp.src(path.resolve(config.projSrc, './static/modules/**/*.js'))
        .pipe(through.obj(function (file, enc, cb) {
            var content = file.contents.toString();
            if (content.indexOf('//@ sourceURL=') == -1) {
                var url = file.path.replace(/^.*?static/, '\\static').replace(/\\/g, '/');
                console.log(url)
                content = `//@ sourceURL=${url}\n\n` + content;
                file.contents = new Buffer(content);
            }
            this.push(file);
            cb();
        }))

        .pipe(gulp.dest(path.resolve(config.projSrc, './static/modules')));
});

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


gulp.task('modules', function () {
    return gulp.src('F:/workspace/picc/picc-admin/src/main/resources/static/modules/**/*.js')
        .pipe(gulp.dest('./dist/temp/modules'))
})


gulp.task('js', function () {
    return gulp.src('F:/workspace/picc/picc-admin/src/main/resources/static/js/**/*.js')
        .pipe(gulp.dest('./dist/temp/js'))
})


gulp.task('toModules', ['modules'], function (done) {
    return gulp.src('./dist/temp/modules/**/*.js')
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('./dist/static/modules'))
});

gulp.task('toJs', ['js'], function (done) {
    return gulp.src('./dist/temp/js/**/*.js')
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('./dist/static/js'))
});

gulp.task('m', function (done) {
    return runSequence(['_clean'], ['B', 'toModules', 'toJs'], done);
})

gulp.task('A', function (done) {
    return gulp.src('F:/workspace/picc/picc-admin/src/main/resources/static/**/*.css')

        .pipe(gulp.dest('./dist/temp'))
})

gulp.task('B', ['A'], function (done) {
    return gulp.src('./dist/temp/**/*.css')
        .pipe(autoprefixer({
            browsers: ['last 99 versions', 'Android >= 4.0'],
            cascade: true,
            remove: true
        }))
        .pipe(gulp.dest('./dist/static'))
})


gulp.task('_test_js', function () {
    // gulp.src('./js/common.js')
    //     .pipe(uglify())
    //     .pipe(gulp.dest('dist/js'));
    gulp.src('./js/index.js')
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(uglify().on('error', function (err) {
            console.log(err);
            this.emit('end');
        }))
        .pipe(gulp.dest('dist/js'));
});